#include "../include/dir.h"

int handle_ls(session_t *session, MYSQL *mysql, int netfd, const char*destDir){
    char buf[1024] = {0};

    int destDirID = -1; //目标目录ID
    
    //if(destDir == NULL||strlen(destDir)==0){
    if(strcmp(destDir,"gg")==0){
        //NULL和strlen=0 即ls无参数
        destDirID = session->curDirID;
    }
    else{
        // ls有参数
        int ret = make_id_path(session, mysql, destDir, &destDirID);
        if(ret != 0){
            strncpy(buf, "参数错误.", sizeof(buf)-1);
            sendtlv(netfd, buf);
            return -1;
        }
    }

    char query[MAX_QUERY_LEN] = {0};
    sprintf(query, "select filename,filetype from file where username = '%s' and parent_id = %d and tomb = 0",
            session->username, destDirID);
    int ret = mysql_query(mysql, query);
    MYSQL_QUERY_CHECK(ret, mysql);

    MYSQL_RES *table = mysql_store_result(mysql);
    MYSQL_STORE_RESULT_CHECK(table, mysql);

    long rows = mysql_num_rows(table);//行数
    if(rows < 1){
        sprintf(buf,"目录为空.");
        sendtlv(netfd,buf);
        return -1;
    }
    for(long i = 0; i < rows; i++){
        MYSQL_ROW row = mysql_fetch_row(table);
        strncat(buf, row[0], sizeof(buf)-strlen(buf)-1);//filename
        if(strcmp(row[1],"d") == 0){
            //说明是目录 末尾加 /
            strncat(buf, "/", sizeof(buf)-strlen(buf)-1);
        }
        strncat(buf, "\n", sizeof(buf)-strlen(buf)-1);
    }
    mysql_free_result(table);
    sendtlv(netfd, buf);
    return 0;
}
